//! # 框架生命周期管理实现
//! 
//! 本模块提供了RustCloud框架的生命周期管理实现。

use crate::framework::traits::*;
use crate::framework::core::RustCloudFramework;
use rustcloud_core::{ServiceResult, ServiceError};
use rustcloud_registry::ServiceRegistry;
use rustcloud_metrics::MetricsCollector;
use std::sync::Arc;
use tokio::sync::RwLock;
use tracing::{info, warn, error};

#[async_trait::async_trait]
impl FrameworkLifecycle for RustCloudFramework {
    /// 启动框架
    pub async fn start(&self) -> ServiceResult<()> {
        info!("启动 RustCloud 框架...");
        
        // 更新状态为初始化中
        {
            let mut state = self.state.write().await;
            *state = FrameworkState::Initializing;
        }

        // 执行启动钩子
        if let Err(e) = self.lifecycle_manager.execute_startup_hooks().await {
            error!("执行启动钩子失败: {}", e);
            let mut state = self.state.write().await;
            *state = FrameworkState::Error(format!("启动钩子失败: {}", e));
            return Err(e);
        }

        // 初始化指标收集
        if let Some(ref metrics) = self.metrics_collector {
            self.initialize_metrics(metrics.clone()).await?;
        }

        // 注册服务到注册中心
        if let Err(e) = self.registry.register(self.service_instance.clone()).await {
            error!("服务注册失败: {}", e);
            let mut state = self.state.write().await;
            *state = FrameworkState::Error(format!("服务注册失败: {}", e));
            return Err(e);
        }

        // 启动健康检查服务
        self.start_health_check_server().await?;

        // 启动指标导出服务
        if self.config.monitoring.metrics.enabled {
            self.start_metrics_server().await?;
        }

        // 启动管理控制台（如果启用）
        if let Some(admin_port) = self.config.network.admin_port {
            self.start_admin_server(admin_port).await?;
        }

        // 更新状态为运行中
        {
            let mut state = self.state.write().await;
            *state = FrameworkState::Running;
        }

        info!("RustCloud 框架启动成功，服务实例: {}", self.service_instance.id);
        Ok(())
    }

    /// 停止框架
    pub async fn stop(&self) -> ServiceResult<()> {
        info!("停止 RustCloud 框架...");

        // 更新状态为停止中
        {
            let mut state = self.state.write().await;
            *state = FrameworkState::Stopping;
        }

        // 从注册中心注销服务
        if let Err(e) = self.registry.deregister(&self.service_instance.id).await {
            warn!("服务注销失败: {}", e);
        }

        // 执行关闭钩子
        if let Err(e) = self.lifecycle_manager.execute_shutdown_hooks().await {
            warn!("执行关闭钩子失败: {}", e);
        }

        // 停止指标收集
        if let Some(ref metrics) = self.metrics_collector {
            // TODO: 实现指标收集器的关闭逻辑
            info!("停止指标收集");
        }

        // 更新状态为已停止
        {
            let mut state = self.state.write().await;
            *state = FrameworkState::Stopped;
        }

        info!("RustCloud 框架停止成功");
        Ok(())
    }

    /// 获取框架状态
    pub async fn get_state(&self) -> FrameworkState {
        self.state.read().await.clone()
    }

    /// 健康检查
    pub async fn health_check(&self) -> ServiceResult<HealthStatus> {
        let mut status = HealthStatus {
            status: HealthLevel::Healthy,
            components: HashMap::new(),
            timestamp: std::time::SystemTime::now(),
        };

        // 检查注册中心连接
        match self.registry.health_check().await {
            Ok(_) => {
                status.components.insert("registry".to_string(), ComponentHealth {
                    level: HealthLevel::Healthy,
                    message: None,
                    details: HashMap::new(),
                });
            },
            Err(e) => {
                status.components.insert("registry".to_string(), ComponentHealth {
                    level: HealthLevel::Unhealthy,
                    message: Some(format!("注册中心连接失败: {}", e)),
                    details: HashMap::new(),
                });
                status.status = HealthLevel::Unhealthy;
            }
        }

        // 检查熔断器状态
        if let Some(ref cb) = self.circuit_breaker {
            let cb_status = if cb.is_open().await {
                HealthLevel::Warning
            } else {
                HealthLevel::Healthy
            };
            status.components.insert("circuit_breaker".to_string(), ComponentHealth {
                level: cb_status,
                message: None,
                details: HashMap::new(),
            });
        }

        // 执行自定义健康检查
        match self.lifecycle_manager.execute_health_checks().await {
            Ok(healthy) => {
                if !healthy {
                    status.status = HealthLevel::Unhealthy;
                    status.components.insert("custom_checks".to_string(), ComponentHealth {
                        level: HealthLevel::Unhealthy,
                        message: Some("自定义健康检查失败".to_string()),
                        details: HashMap::new(),
                    });
                }
            },
            Err(e) => {
                status.status = HealthLevel::Unhealthy;
                status.components.insert("custom_checks".to_string(), ComponentHealth {
                    level: HealthLevel::Error,
                    message: Some(format!("健康检查执行失败: {}", e)),
                    details: HashMap::new(),
                });
            }
        }

        Ok(status)
    }
}

impl RustCloudFramework {
    /// 检查框架是否运行中
    pub async fn is_running(&self) -> bool {
        matches!(*self.state.read().await, FrameworkState::Running)
    }
}